<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class auth_model extends CI_Model
{
    public function auth_model()
    {
        parent::__construct();
    }
    //---------- Login function
    public function checkUserLogin($params)
    {
        $sql = "SELECT *, GROUP_CONCAT(rid) as rolelist from (
            	SELECT `u`.*, `r`.`rid` 
            	FROM (`users` u) 
            	LEFT JOIN `users_roles` r ON `r`.`uid` = `u`.`id` 
            	WHERE `u`.`username` = ? AND `u`.`pass` = ? )
            temp group by id";
        $query = $this->db->query($sql, array($params['username'], $params['pass']));
        return $query->row_array();
    }

    /**
     *  check user Active
     */
    public function isActive($username)
    {
        $query = $this->db->get_where('users', array('username' => $username, 'status' => 1));
        if ($query->num_rows() > 0)
            return true;
        return false;
    }

    /**
     *  register session login
     */
    public function addSession($params)
    {
        $this->session->set_userdata(array('userInfo' => $params));
        $_SESSION["CI_LOGIN"] = "ok";
    }

    public function userInfo()
    {
        return $this->session->userdata('userInfo');
    }
    /**
     * return true if logged and false if not logged
     */
    public function isLogin()
    {
        if (!isset($_SESSION["CI_LOGIN"]) || $_SESSION["CI_LOGIN"] != 'ok')
            return false;
        return true;
    }

    public function userid()
    {
        $userInfo = $this->session->userdata('userInfo');
        return $userInfo['id'];
    }

    public function username()
    {
        $userInfo = $this->session->userdata('userInfo');
        return $userInfo['username'];
    }

    public function rid()
    {
        $userInfo = $this->session->userdata('userInfo');
        $roles = $userInfo['rolelist'];
        return explode(',', $roles);
    }
    
    public function acl()
    {
        $arrRoles = $this->rid();
        $strRole = implode(',', $arrRoles);
        $sql = "SELECT * FROM role where rid in ($strRole)";
        $query = $this->db->query($sql);
        return $query->row_array();
    }
}
